import store from '../redux/store/store'
import Utils from '../helpers/utils'
import Config from './config'
import RNFetchBlob from 'react-native-fetch-blob'
import {Platform} from 'react-native'
import youdaoSdkUrl from '../helpers/youdaoSdk'
//当前用户
const current_user = () => store.getState().user.user || {}
const role = () => store.getState().isLeader?3:1

//默认的GET Header
const _GET_ = () =>  {
    return {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Version-Code': App.version,
            'Token': current_user().token || ''
        }
    }
}

//默认的POST Header
const _POST_ = (body) => {
    return(
            {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                    'Version-Code': App.version,
                    'Token': current_user().token || ''
                },
                body: JSON.stringify(body)
            } 
        )
}

//默认的PUT Header
const _PUT_ = (body) => {
    return(
        {
            method: 'PUT',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'Version-Code': App.version,
                'Token': current_user().token || ''
            },
            body: JSON.stringify(body)
        } 
    )
}


//通用的请求生成器
class Requester {
    constructor(header={}, url) {
        this.host = App.host
        // this.host = 'http://test.oral2.wfl-ischool.cn'
        this.version = "v1"
        this.url = url
        this.header = header
    }

    do_fetch (url_improvement=true) {
        return new Promise((resolve, reject) => {
            let timeout = setTimeout(() => {reject("请求超时")}, 20000)
            let _url = url_improvement ? `${this.host}/api/${this.version}${this.url}` : this.url
            console.log('_url', _url)
            fetch(_url, this.header).then((response) => {
                clearTimeout(timeout)
            if (response.status.toString().match(/^2.*/)) {
                    return response.json()
                } else {
                    return reject(response.status)
                }
            }).then((responseData) => {
                if (responseData.code == 200401 ) {
                    alert('版本错误')
                    return(reject('版本错误'))
                }
                return resolve(responseData)
            }).catch((error) => {
                return reject(error)
            })
        })
    }
}

const AWS = require('aws-sdk/dist/aws-sdk-react-native');

//aws3 sdk设置
AWS.config.update({
    region: 'cn-north-1', 
    accessKeyId: 'AKIAOW6O274SCMWU42QA',
    secretAccessKey: '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', 
    dynamoDbCrc32: false
});

//初始化一个s3客户端
const s3 = new AWS.S3({
    endpoint: 'https://s3.cn-north-1.amazonaws.com.cn', 
    apiVersion: '2006-03-01',
    signatureVersion: 'v4'
});


//aws3文件上传接口
export const Aws3UploadApi = async (fileName, localPath, contentType, bucketName=App.awsBucketName) => {
    let keyName = `${current_user().login_name}/${fileName}`
    const s3Url = await s3.getSignedUrl('putObject', {
        Bucket: bucketName,
        Key: keyName,
        ContentType: contentType,
        ACL: 'public-read'        
    });

    //ios的file路径需要做一下处理，把'file://'去掉
    if (Platform.OS == 'ios') {
        localPath = localPath.replace(/file:\/\//, '')
    }

    const dirs = RNFetchBlob.fs.dirs
    const remoteUrl = `${s3.config.endpoint + "/" + bucketName + "/" + keyName}`
    const TO_PATH = `${dirs.DocumentDir}/${remoteUrl.replace(/https:\/\/|http:\/\//, '')}`
    console.log('TO_PATH', TO_PATH)

    const result = await RNFetchBlob.fetch('PUT', s3Url, {
        'Content-Type': contentType
    }, RNFetchBlob.wrap(localPath));

    RNFetchBlob.fs.mv(localPath.replace(/file:\/\//, ''), TO_PATH)

    return {
        status: result.respInfo.status,
        awsPath: remoteUrl
    }

}

//有道词典的接口
export const youdaoTranslateApi = (word) => {
    return new Requester(
        {method: 'GET', headers: {'Accept': 'application/json'}}, 
        youdaoSdkUrl(word)
    ).do_fetch(false)
}
  
//登录接口
export const AuthLoginApi = (username, password) => {
    var token_password = Utils.custom_encode(Config.salt_token, password);
    return new Requester(_POST_({username: username, password: token_password}), '/auths/login').do_fetch()
}

//获取配置的接口
export const GetSettingsApi = () => {
    return new Requester(_GET_(), '/settings').do_fetch()
}

//作业列表接口
export const GetHomeworksApi = (page, filter=null, created_at="") => {
    return new Requester(_GET_(), `/homeworks?page=${page}&role=${role()}&id=${current_user().id}&filter=${filter}&created_date=${created_at}`).do_fetch()
}

/*
    body: {
        lesson_teacher_id: 0,
        title: "",
        needReply: true,
        needScore: true,
        description: "",
        chapter_id: 0,
        students: [1, 2, 3, 4 ,5 ],
        attachments: {
            url: "",
            name: "",
            type: ""
        }
    }
 */
//新建作业的接口
export const PostCreateHomeworkAPi = (body) => {
    return new Requester(_POST_(body), '/homeworks').do_fetch()
}

//作业详情接口
export const GetHomeworkApi = (id) => {
    return new Requester(_GET_(),`/homeworks/${id}`).do_fetch()
}

//新建作业获取学科选择的接口
export const GetSelectLessonsApi = () => {
    return new Requester(_GET_(), `/lessons`).do_fetch()
}

//新建作业获取课本选择的接口
export const GetSelectTextbooksApi = (lesson_teacher_id='') => {
    return new Requester(_GET_(), `/lessons/textbooks?lesson_teacher_id=${lesson_teacher_id}`).do_fetch()
}

//通过年级选择课本的接口
export const GetGradeTextBooksApi = (grade_id) => {
    return new Requester(_GET_(), `/lessons/${grade_id}/grade_textbooks`).do_fetch()
}

//新建作业获取章节选择的接口
export const GetSelectChaptersApi = (textbook_id) => {
    return new Requester(_GET_(), `/lessons/chapters?textbook_id=${textbook_id}`).do_fetch()
}

export const getUnitChaptersApi = (first_unit_id) => {
    return new Requester(_GET_(), `/lessons/${first_unit_id}/unit_chapters`).do_fetch()
}

//获取课文的接口
export const GetChapterSectionsApi = (chapter_id) => {
    return new Requester(_GET_(), `/lessons/${chapter_id}/chapter_section`).do_fetch()
}

//点击班级获取学生的接口
export const GetSelectStudentsApi = (classroom_id) => {
    return new Requester(_GET_(), `/students?classroom_id=${classroom_id}`).do_fetch()
}

//answer详情接口
export const GetAnswerApi = (id, studentid) => {
    return new Requester(_GET_(),`/answers?homeworkid=${id}&studentid=${studentid}`).do_fetch()
}

//提交answer
/*
     body: {
        attachemts: Array,
        id: Answer的ID,
        content: String
    }
*/
export const PostAnswerApi = (body) => {
    return new Requester(_POST_(body), '/answers').do_fetch()
}

//撤回homework
export const PutRetractHomeworkApi = (id,homework_id,locationType=null) => {
    return new Requester(_PUT_({homework_id: homework_id, locationType: locationType}), `/recall/${id}`).do_fetch()
}

//撤回answer
export const PutRetractAnswerApi = (id, homework_id, locationType=null) => {
    return new Requester(_PUT_({homework_id: homework_id, locationType: locationType}), `/answers/${id}/recall`).do_fetch()
}

export const PutRetractTaskApi = (task_answer_id) => {
    return new Requester(_PUT_(), `/task_answers/${task_answer_id}/recall`).do_fetch()
}

//撤回新版的作业
export const PutRetractNewHomeworkApi = (homework_id) => {
    return new Requester(_PUT_(), `/homeworks/${homework_id}/recall`).do_fetch()
}

//撤回reply
export const PutRetractReplyApi = (id) => {
    return new Requester(_PUT_(), `/replies/${id}/recall`).do_fetch()
}

//撤回task_reply
export const PutRetractTaskReplyApi = (id) => {
    return new Requester(_PUT_(), `/task_replies/${id}/recall`).do_fetch()
}

//通知列表接口
export const GetNofiticationsApi = (page, filter=null, created_at="") => {
    return new Requester(_GET_(), `/notifications?page=${page}&filter=${filter}&role=${current_user().role}&id=${current_user().id}&created_at=${created_at}`).do_fetch()
}

//通知详情接口
export const GetNofiticationApi = (id, studentid=null) => {
    return new Requester(_GET_(), `/notifications/notianswers?notificationid=${id}&studentid=${studentid}`).do_fetch()
}

/*
    body: {
        title: "",
        description: "",
        students: [],
        attachments: []
    }
 */
//创建通知的接口
export const PostCreateNotificationApi = (body) => {
    return new Requester(_POST_(body), '/notifications').do_fetch()
}

//通知查看接口
export const GetNotificationCorrectApi = (id) => {
    return new Requester(_GET_(), `/notifications/${id}`).do_fetch()
}

//老师批改作业的接口
/* 
    body: {
        isFinish: true | false ,
        attachemts: Array,
        score: 0..10.0,
        id: Reply的ID,
        content: String
    }
*/
export const PostTeacherReplyApi = (body) => {
    return new Requester(_POST_(body), '/replies').do_fetch()
}

//书本列表的接口
export const GetTextBooksApi = () => {
    return new Requester(_GET_(), '/chapters/textbooks').do_fetch()
}

//课程列表的接口
export const GetChaptersApi = (textbook_id=null) => {
    return new Requester(_GET_(), `/chapters?textbook_id=${textbook_id}`).do_fetch()
}

//获取排行榜数据
export const GetRankingListApi = () => {
    return new Requester(_GET_(), '/chapters/ranking_list').do_fetch()
}

//课程详情的接口
export const GetChapterApi = (id) => {
    return new Requester(_GET_(), `/sentences?section_id=${id}`).do_fetch()
}

//意见反馈
export const PostFeedbackApi = (content) => {
    return new Requester(_POST_({content: content}), '/feedbacks').do_fetch()
}


//录音完毕上传测评统计数据
export const saveExerciseData = (id,content) => {
    return new Requester(_POST_({sentence: content}), `/sentences/${id}/record_score`).do_fetch();
}

//挑战完成上传测评统计数据
export const saveChallengeScore = (chapter_id,id,score) => {
    return new Requester(_POST_({chapter_id: chapter_id,score: score}), `/chapters/${id}/record_score`).do_fetch();
}

//获取年级的接口
export const GetGradesApi = () => {
    return new Requester(_GET_(), '/lessons/grades').do_fetch()
}

//获取task详情
export const GetTaskApi = (id, homework_id) => {
    return new Requester(_GET_(), `/tasks/${id}?homework_id=${homework_id}`).do_fetch()
}

/* 
    body: {
        attachments: []
    }
*/

//提交task音频作业
export const PostTaskAudioApi = (task_id, body) => {
    return new Requester(_POST_(body), `/tasks/${task_id}/task_student_audio`).do_fetch()
}

//班级统计报表数据
export const GetClassroomReports = () => {
    return new Requester(_GET_(), '/reports/classrooms').do_fetch();
}
//学生统计列表
export const GetStudentReports = () => {
    return new Requester(_GET_(), '/reports/students').do_fetch();
}

//一个班级的发音统计
export const getOneClassroomReport = (id) => {
    return new Requester(_GET_(), `/reports/${id}/classroom`).do_fetch();
}

//某音标学生统计
export const getPhonogramStudents = (id,phonogram_code) => {
    return new Requester(_GET_(), `/reports/${id}/phonogram_students?phonogram_code=${phonogram_code}`).do_fetch();
}

//某学生的发音统计
export const getOneStudentReport = (id) => {
    return new Requester(_GET_(), `/reports/${id}/student`).do_fetch();
}

/*
    body: {
        task_id: Integer
        content: "",
        attachments: []
    }
 */

//学生提交作业补充
export const PostStudentTaskAnswerApi = (body) => {
    return new Requester(_POST_(body), '/task_answers').do_fetch()
}

//老师批改前看同学的接口
export const GetTaskCorrectApi = (task_id, homework_id) => {
    return new Requester(_GET_(), `/tasks/${task_id}?homework_id=${homework_id}`).do_fetch()
} 

//保存用户头像
export const saveUserHeader = (avatar) => {
    return new Requester(_POST_({avatar: avatar}), `/users`).do_fetch();
}

//获取学生作业信息
export const GetTaskStudent = (task_id, student_id) => {
    return new Requester(_GET_(), `/tasks/${task_id}/task_student?student_id=${student_id}`).do_fetch()
}

//新版老师批改
export const PostTaskReplyApi = (body) => {
    return new Requester(_POST_(body), '/task_replies').do_fetch()
}

